package com.xuecheng.media.service.impl;

import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.commons.constants.CommonConstants;
import com.xuecheng.commons.constants.MediaConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.*;
import com.xuecheng.commons.model.vo.*;
import com.xuecheng.commons.utils.AuthInfoThreadLocal;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.commons.utils.TimeUtils;
import com.xuecheng.content.api.ContentClient;
import com.xuecheng.media.config.VodTemplate;
import com.xuecheng.media.domain.Media;
import com.xuecheng.media.mappers.MediaMapper;
import com.xuecheng.media.service.MediaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exceptions.BusinessException;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 媒资信息 服务实现类
 * </p>
 *
 * @author 七安
 * @since 2022-09-22
 */
@Service
public class MediaServiceImpl extends ServiceImpl<MediaMapper, Media> implements MediaService {

    @Autowired
    private MediaMapper mediaMapper;

    @Autowired
    private VodTemplate vodTemplate;

    @Autowired
    private ContentClient teachplanMediaClent;

    /**
     * 获取阿里云上传token
     *
     * @return 上传地址，上传凭证
     */
    @Override
    public ResponseResult<VodUploadVo> getUploadToken(VodUploadDto vodUploadDto) throws BusinessException, ClientException {
        //获取视频标题
        String title = vodUploadDto.getTitle();
        //获取视频源文件名
        String fileName = vodUploadDto.getFileName();
        //判空
        if (StringUtils.isEmpty(title) || StringUtils.isEmpty(fileName)) {
            //抛出上传阿里云失败异常
            throw new BusinessException(ErrorCode.ALIYUNERROR);
        }
        //调用vodTemplate获取上传地址和凭证
        CreateUploadVideoResponse uploadVideo = vodTemplate.createUploadVideo(title, fileName);
        //封装返回值
        VodUploadVo vodUploadVo = new VodUploadVo();
        //bean复制
        BeanUtils.copyProperties(uploadVideo, vodUploadVo);
        //设置用户id
        vodUploadVo.setUserId(AuthInfoThreadLocal.getUserId().toString());
        //返回对象
        return ResponseResult.okResult(vodUploadVo);
    }

    /**
     * 刷新上传token
     *
     * @param videoId 视频id
     * @return 上传地址和凭证
     */
    @Override
    public ResponseResult<VodUploadVo> refreshUploadToken(String videoId) throws ClientException {
        //调用vodTemplate
        RefreshUploadVideoResponse response = vodTemplate.refreshUploadVideo(videoId);
        //创建返回对象
        VodUploadVo vodUploadVo = new VodUploadVo();
        //bean复制
        BeanUtils.copyProperties(response, vodUploadVo);
        //设置用户id
        vodUploadVo.setUserId(AuthInfoThreadLocal.getUserId().toString());
        return ResponseResult.okResult(vodUploadVo);
    }

    /**
     * 保存媒资信息
     *
     * @param mediaDto 要保存的内容
     * @return 结果
     */
    @Override
    public ResponseResult saveMedia(MediaDto mediaDto) throws ClientException, BusinessException {
        //判空
        if (ObjectUtils.isEmpty(mediaDto)) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        //转成实体对象
        Media media = BeanHelper.copyProperties(mediaDto, Media.class);
        //设置机构id
        media.setCompanyId(AuthInfoThreadLocal.getCompanyId());
        //设置机构名字
        media.setCompanyName(AuthInfoThreadLocal.getAuthInfo().getCompanyName());
        //设置审核状态
        media.setAuditStatus(MediaConstants.AUDIT_UNPAST_STATUS);
        //根据传来的视频id查询url和视频时长
        GetPlayInfoResponse response = vodTemplate.getPlayInfo(mediaDto.getFileId());
        //获取playInfo集合
        List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
        //取第一条元素
        GetPlayInfoResponse.PlayInfo playInfo = playInfoList.get(0);
        media.setUrl(playInfo.getPlayURL());
        //视频时长转换
        String duration = playInfo.getDuration();
        Double time = new Double(duration);
        duration = TimeUtils.secondToTime(time);
        media.setTimelength(duration);
        //保存到数据库
        mediaMapper.insert(media);
        return ResponseResult.okResult();
    }

    /**
     * 分页查询媒资信息
     *
     * @param pageRequest   分页条数...
     * @param mediaQueryDto 媒资查询封装类
     * @return 查到的数据
     */
    @Override
    public PageResponseResult<MediaVo> findMediaList(PageRequest pageRequest, MediaQueryDto mediaQueryDto) {
        //分页对象
        Page<Media> mediaPage = new Page<>(pageRequest.getPageNo(), pageRequest.getPageSize());
        //查询wrapper
        LambdaQueryWrapper<Media> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(mediaQueryDto.getFilename()), Media::getFilename, mediaQueryDto.getFilename());
        wrapper.eq(StringUtils.isNotEmpty(mediaQueryDto.getType()), Media::getType, mediaQueryDto.getType());
        wrapper.eq(StringUtils.isNotEmpty(mediaQueryDto.getAuditStatus()), Media::getAuditStatus, mediaQueryDto.getAuditStatus());
        //查询
        mediaPage = mediaMapper.selectPage(mediaPage, wrapper);
        //总条数
        long total = mediaPage.getTotal();
        //结果list
        List<MediaVo> mediaVos = BeanHelper.copyWithCollection(mediaPage.getRecords(), MediaVo.class);
        return new PageResponseResult(total, mediaVos);
    }

    /**
     * 审核媒资
     *
     * @param mediaAuditDto 审核意见和状态
     * @return 审核结果
     */
    @Override
    public ResponseResult verifyMedia(MediaAuditDto mediaAuditDto) throws BusinessException {
        //判断当前媒资的状态
        Media media = mediaMapper.selectById(mediaAuditDto.getId());
        //判空和状态
        if (media == null || MediaConstants.AUDIT_PASTED_STATUS.equals(media.getAuditStatus())) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        //设置审核状态
        media.setAuditStatus(mediaAuditDto.getAuditStatus());
        //设置审核意见
        media.setAuditMind(mediaAuditDto.getAuditMind());
        //更新数据库
        mediaMapper.updateById(media);
        return ResponseResult.okResult();
    }

    /**
     * 根据id预览视频
     *
     * @param mediaId 媒资id
     * @return 结果
     */
    @Override
    public ResponseResult<String> getMediaUrl(Long mediaId) throws BusinessException {
        //根据id查询
        Media media = mediaMapper.selectById(mediaId);
        //判空
        if (ObjectUtils.isEmpty(media) || StringUtils.isEmpty(media.getUrl())) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        return ResponseResult.okResult(media.getUrl());
    }

    /**
     * 根据id删除媒资
     *
     * @param mediaId 要删除的媒资id
     * @return 结果
     */
    @Override
    public ResponseResult<Boolean> deleteMediaById(Long mediaId) throws Exception {
        //根据id查询
        Media media = mediaMapper.selectById(mediaId);
        //判空
        if (ObjectUtils.isEmpty(media) || CommonConstants.DELETE_FLAG.equals(media.getStatus())) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        //判断当前媒资是否有被绑定
        ResponseResult<TeachplanMediaDataVo> responseResult = teachplanMediaClent.findTmByMediaId(mediaId);
        TeachplanMediaDataVo data = responseResult.getData();
        //如果不是空的，证明被绑定呢   不能删
        if (ObjectUtils.isNotEmpty(data)) {
            throw new BusinessException(ErrorCode.DELETEERROR);
        }
        mediaMapper.deleteById(media);
        vodTemplate.deleteVideo(media.getFileId());
        return ResponseResult.okResult(true);
    }

    /**
     * 根据id获取媒资URL地址
     *
     * @param mediaId id
     * @return 结果
     */
    @Override
    public ResponseResult<ResourceVo> gainMediaUrl(Long mediaId) throws BusinessException, ClientException {
        //判空
        if (mediaId == null) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        //根据id查询媒资信息
        Media media = mediaMapper.selectById(mediaId);
        //根据视频id获取播放链接
        GetPlayInfoResponse response = vodTemplate.getPlayInfo(media.getFileId());
        //获取playInfo集合中的第0个元素
        GetPlayInfoResponse.PlayInfo playInfo = response.getPlayInfoList().get(0);
        ResourceVo resourceVo = new ResourceVo();
        resourceVo.setPlayUrl(playInfo.getPlayURL());
        return ResponseResult.okResult(resourceVo);
    }
}
